import React, { useEffect, useState, useRef, useCallback } from 'react';
import { connect } from 'umi';
import { Form, Button, Row, Col, Divider, Space, Tag, notification } from 'antd';
import FormCondition from '@/components/FormCondition';
import DrawerCondition from '@/components/DrawerCondition';
import FormComponents from '../FormComponents'
import { DeleteOutlined } from '@ant-design/icons';
import aliOssUpload from '@/utils/aliOssUpload';
const SetForm = (props) => {
    const { dispatch, visible = {}, onClose, handleCallback, loading, wxPageList = [], active } = props;
    const { show = false, detail = [] } = visible;
    const [list, setList] = useState([])
    const formRefs1 = useRef({});
    const formRefs2 = useRef({});
    const formRefs3 = useRef({});
    const formRefs4 = useRef({});
    const formRefs5 = useRef({});
    const formRefs6 = useRef({});
    const formRefs7 = useRef({});
    const formRefs8 = useRef({});
    const formRefs9 = useRef({});
    const formRefs10 = useRef({});
    const formRefs11 = useRef({});
    const formRefs12 = useRef({});
    const formRefs13 = useRef({});
    const formRefs14 = useRef({});
    const formRefs15 = useRef({});
    const formRefs16 = useRef({});
    const formRefs17 = useRef({});
    const formRefs18 = useRef({});
    const formRefs19 = useRef({});
    const formRefs20 = useRef({});
    const [refList, setRefList] = useState([
        formRefs1,
        formRefs2,
        formRefs3,
        formRefs4,
        formRefs5,
        formRefs6,
        formRefs7,
        formRefs8,
        formRefs9,
        formRefs10,
        formRefs11,
        formRefs12,
        formRefs13,
        formRefs14,
        formRefs15,
        formRefs16,
        formRefs17,
        formRefs18,
        formRefs19,
        formRefs20,
    ])
    useEffect(() => {
        if (show) {
            if (detail.length > 0) {
                setList([...detail])
            }
            else {
                setList([{}])
            }
        }
        else {
            setList([])
        }
    }, [show])
    const handleDelete = (index) => {
        if (list.length <= 1) {
            // 如果只剩最后一个，不清空而是重置为空对象
            setList([{}]);
        } else {
            console.log(index)
            setList(list.filter((_, i) => i !== index));
        }
    };
    const getField = () => {
        const arr = []
        list.forEach((val, index) => {
            arr.push(<div
                key={index}
                style={{
                    border: '1px solid #e8e8e8',
                    borderRadius: '4px',
                    padding: '16px',
                    position: 'relative',
                    backgroundColor: '#fafafa',
                }}
            >
                <Button
                    style={{
                        position: 'absolute',
                        top: '8px',
                        right: '8px',
                    }}
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => handleDelete(index)}
                    disabled={list.length === 1}
                    size="small"
                />
                <FormComponents index={index} ref={refList[index]} wxPageList={wxPageList} initialValues={val}></FormComponents>
            </div>)
        })
        return arr
    }
    const fetchRoleEdit = async () => {
        const uploadList = refList.filter(val => {
            return val && val.current && val.current.form
        }).map(val => {
            return val.current.form.validateFields
        })
        await Promise.all(uploadList.map(val => { return val() })).then(async value => {
            await Promise.all(value.map(async (formData) => {
                // 如果formData.image是File对象（或者类似文件对象），则上传
                const { cover } = formData
                const imageUrl = await aliOssUpload(cover)
                return { ...formData, cover: imageUrl.toString() };
            })).then(val => {
                dispatch({
                    type: 'marketing/fakeSaveBanner',
                    payload: {
                        bannerType: active,
                        bannerList: val
                    },
                    callback: (e) => {
                        handleCallback()
                        onClose()
                    }
                })
            })
        }).catch(val => {
            // notification.warning({
            //     message: '温馨提示',
            //     description: '图片上传失败',
            // })
        })
    };


    const modalProps = {
        title: `设置banner`,
        visible: show,
        width: 640,
        extra: <Button disabled={list.length > 20} onClick={() => {
            setList([...list, {}])
        }}>新增</Button>,
        onClose,
        footer: <Button type="primary" loading={loading} onClick={fetchRoleEdit}>
            确定
        </Button>,
    };
    return (
        <DrawerCondition {...modalProps}>
            <Space direction='vertical' style={{ width: '100%' }}>
                {getField()}
            </Space>
        </DrawerCondition >
    );
};

export default connect(({ loading }) => ({
    loading: loading.effects['user/fakeCombineUser'],
}))(SetForm);
